
import { Api } from '@/api'
import { TOKEN } from '@/store/const'
import { useUserStore } from '@/store/user'
import { storageLocal } from '@wxcn/utils'

export function useToken() {
  const { setToken, clearUserInfo } = useUserStore()
  const refreshToken = async () => {
    const _token = storageLocal.getItem(TOKEN)
    if (!_token?.RefreshToken)
      return
    try {
      const res = await Api.AccountService.RefreshToken(_token?.RefreshToken)
      setToken(res)
    }
    catch (error: any) {
      console.error(error)
      if (error?.request?.status === 401) {
        clearUserInfo()
      }
    }
    finally {
      setTimeout(refreshToken, 1000 * 60)
    }
  }

  return {
    refreshToken,
  }
}
